﻿using System;

using System.Security;
using System.Security.Principal;

using System.Windows.Forms;

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;

using CodePlex.Diagnostics;
using CodePlex.Diagnostics.Providers;

using Microsoft.SqlServer.MessageBox;

namespace CodePlex.SqlGenerator
{
    static class Program
    {
        #region private static void Main(string[] args)

        /// <summary>
        /// Defines the program entry point.
        /// </summary>
        /// <param name="args">A <see cref="T:System.String"/> array containing any command line arguments specified at runtime.</param>
        [STAThread]
        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "args")]
        private static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            SqlGeneratorForm mainForm = new SqlGeneratorForm();

            SqlGeneratorContext context = new SqlGeneratorContext(mainForm);

            Application.Run(context);
        }

        #endregion

        #region private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)

        /// <summary>
        /// Handles the <see cref="M:System.AppDomain.UnhandledException"/> event of the current <see cref="T:System.AppDomain"/>.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.UnhandledExceptionEventArgs"/> instance containing the event data.</param>
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;

            if(ex != null)
            {
                IIdentity identity = WindowsIdentity.GetCurrent() as IIdentity;
                ExceptionProvider.Publish(ex, identity);

                ExceptionMessageBox messageBox = new ExceptionMessageBox(ex);

                messageBox.Show(SqlGeneratorContext.SqlGenerator);
            }

            Application.Exit();
        }

        #endregion
    }
}
